package com.lwk;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

public class ESTest_Doc_Insert {

    public static void main(String[] args) throws Exception {

        // 创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));

        // 插入数据
        IndexRequest request = new IndexRequest();
        request.index("user").id("1001");

        UserIndex userIndex = new UserIndex("zhangSan","男",30);

        ObjectMapper mapper = new ObjectMapper();
        String userJson = mapper.writeValueAsString(userIndex);

        request.source(userJson, XContentType.JSON);
        IndexResponse indexResponse = esClient.index(request, RequestOptions.DEFAULT);

        // 响应
        System.out.println(indexResponse.getResult());

        // 关闭ES客户端
        esClient.close();


    }

}
